/*
 * Galaxium Messenger
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;

using Mono.Addins;

using Anculus.Core;

using Galaxium.Core;

namespace Galaxium.Gui
{
	public static class HTMLUtility
	{
		static Type _widgetType = null;
		
		const string _htmlWidgetPath = "/Galaxium/Gui/Widgets/Html";
		
		/// <value>
		/// The type of the last created HTML widget
		/// </value>
		public static Type WidgetType
		{
			get { return _widgetType; }
		}
		
		static HTMLUtility ()
		{
			AddinManager.ExtensionChanged += OnExtensionChanged;
		}
		
		/// <summary>
		/// Create a HTML widget
		/// </summary>
		/// <returns>
		/// The <see cref="IHTMLWidget"/>
		/// </returns>
		public static IHTMLWidget CreateHTMLWidget ()
		{
			if (_widgetType != null)
				return Activator.CreateInstance (_widgetType) as IHTMLWidget;
			
			//TODO: Load desired backend from config
			IHTMLWidget widget = CreateHTMLWidget ("WebKit");
			
			if (widget != null)
				return widget;
			
			widget = CreateHTMLWidget (null);
			
			if (widget != null)
				return widget;
			
			Log.Warn ("Unable to create HTML widget");
			return null;
		}
		
		static IHTMLWidget CreateHTMLWidget (string name)
		{
			foreach (HTMLWidgetExtension node in AddinUtility.GetExtensionNodes (_htmlWidgetPath))
			{
				if (!(string.IsNullOrEmpty (name) || (node.Id == name)))
					continue;
				
				try
				{
					IHTMLWidget widget = node.GetWidget ();
					_widgetType = node.WidgetType;
					
					//Log.Debug ("Created {0} HTML widget", widget);
					
					return widget;
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					bool dllNotFound = false;
					
					while (ex2 != null)
					{
						if (ex2 is DllNotFoundException)
						{
							dllNotFound = true;
							break;
						}
						
						ex2 = ex2.InnerException;
					}
					
					if (dllNotFound)
						Log.Info ("{0} not present ({1})", node.Id, ex2.Message);
					else
						Log.Warn (ex, "Unable to create {0} HTML widget", node.Id);
				}
			}
			
			return null;
		}
		
		static void OnExtensionChanged (object o, ExtensionEventArgs args)
		{
			if (args.PathChanged (_htmlWidgetPath))
				_widgetType = null;
		}
	}
}
